package com.zkgengkun.console.service.impl;

import com.zkgengkun.console.service.UserService;
import com.zkgengkun.domain.User;
import com.zkgengkun.repository.UserRepository;
import com.zkgengkun.support.util.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

/**
 * @author gengshikun
 * @date 2016/12/6
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public void save(User user) {
        this.userRepository.save(user);
    }

    @Override
    public Page getListForPage(String query, Integer pageNo) {
        Page<User> pager = null;

        if (StringUtils.isNotBlank(query)) {
            pager = this.userRepository.findByNameLike(query, PageUtils.buildPageRequest(pageNo));
        } else {
            pager = this.userRepository.findAll(PageUtils.buildPageRequest(pageNo));
        }

        return pager;
    }

    @Override
    public User getOneByEmailAndPassword(String email, String password) {
        return this.userRepository.findByEmailAndPassword(email, password);
    }

    @Override
    public User getOneById(String userId) {
        return this.userRepository.findOne(userId);
    }

    @Override
    public User getOneByEmail(String email) {
        return this.userRepository. findByEmailAndDeleteBoolean(email, Boolean.FALSE);
    }

    /**
     * 更新某个字段
     *
     * @param userId
     * @param onStatus
     */
    @Override
    public void updateValidate(String userId, Boolean onStatus) {
        User user = this.getOneById(userId);
        user.setValidate(onStatus);
        this.userRepository.save(user);
    }
}
